package com.ut.demo.slice;

import ark.system.ClassLoaderCreator;
import ark.system.ClassLoaderHelper;
import com.google.gson.Gson;
import com.ut.demo.ResourceTable;
import com.ut.demo.component.DynamicComponentContainer;
import com.ut.demo.util.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;
import ohos.bundle.IBundleManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.Enumeration;

public class MainAbilitySlice extends AbilitySlice {

    ComponentContainer container;

    Component component;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        container = (ComponentContainer) findComponentById(ResourceTable.Id_container);
        findComponentById(ResourceTable.Id_text).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                container.removeAllComponents();
                container.addComponent(MainAbilitySlice.this.component);
            }
        });

        requestPermission();
    }

    private void requestPermission(){
        if (verifySelfPermission("ohos.permission.READ_MEDIA") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.READ_MEDIA")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(new String[] {"ohos.permission.READ_MEDIA", "ohos.permission.WRITE_MEDIA"} , 0);
            } else {
                // 显示应用需要权限的理由，提示用户进入设置授权
            }
        } else {
            // 权限已被授予
//            test();

        }
    }

    private void test(){
        //  com.kot32.dynamicloadviewlibrary.View com/kot32/dynamicloadviewlibrary/View
        String filePath = getExternalCacheDir()+ File.separator+"plugin.hap";
        String rawFilePath = "entry/resources/rawfile/plugin.hap";
        copyAndWrite(this, filePath, rawFilePath);
        File file = new File(filePath);
        LogUtil.i("slice file exist: %b", file.exists());
        ClassLoader classLoader = ClassLoaderCreator.createClassLoader(filePath, getClassloader());
        component = createView(classLoader, "com.ut.plugin.component.View");
        LogUtil.i("component is null: %b", component==null);
    }

    private Component createView(ClassLoader classLoader, String className){
        try {
            Class claz = classLoader.loadClass(className);
            Constructor constructor = claz.getConstructor(Context.class);
            return (Component) constructor.newInstance(this);
        } catch (Exception e) {
            LogUtil.i("error msg: %s", e.getLocalizedMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将asset文件写入缓存
     */
    private boolean copyAndWrite(Context context, String filePath, String rawFilePath){
        try {
            File outFile =new File(filePath);
            if (!outFile.exists()){
                boolean res=outFile.createNewFile();
                if (!res){
                    return false;
                }
            }else {
                if (outFile.length()>10){//表示已经写入一次
                    return true;
                }
            }
            InputStream is = context.getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
